#include <stdio.h>
#include <math.h>
#include "config.h"
#include <alsa/asoundlib.h>

const char *ATTACH = "default";
const snd_mixer_selem_channel_id_t CHANNEL = SND_MIXER_SCHN_FRONT_LEFT;
const char *SELEM_NAME = "Master";

long vol;
long vol_min, vol_max;

snd_mixer_t *h_mixer;
snd_mixer_selem_id_t *sid;
snd_mixer_elem_t *elem ;

char output_buffer[255];

void volume_initialize() {

  snd_mixer_open(&h_mixer, 1);
  snd_mixer_attach(h_mixer, ATTACH);
  snd_mixer_selem_register(h_mixer, NULL, NULL);
  snd_mixer_load(h_mixer);
  snd_mixer_selem_id_malloc(&sid);
  snd_mixer_selem_id_set_index(sid, 0);
  snd_mixer_selem_id_set_name(sid, SELEM_NAME);
  elem = snd_mixer_find_selem(h_mixer, sid);
  snd_mixer_selem_get_playback_volume_range(elem, &vol_min, &vol_max);
 
}

char *volume_getcurrent() {

  snd_mixer_open(&h_mixer, 1);
  snd_mixer_attach(h_mixer, ATTACH);
  snd_mixer_selem_register(h_mixer, NULL, NULL);
  snd_mixer_load(h_mixer);
  snd_mixer_selem_id_malloc(&sid);
  snd_mixer_selem_id_set_index(sid, 0);
  snd_mixer_selem_id_set_name(sid, SELEM_NAME);
  elem = snd_mixer_find_selem(h_mixer, sid);
  snd_mixer_selem_get_playback_volume_range(elem, &vol_min, &vol_max);
  
  snd_mixer_selem_get_playback_volume(elem, CHANNEL, &vol);
  snd_mixer_close(h_mixer);

  snprintf(output_buffer, sizeof(output_buffer), VOLUME_FORMAT, convert_range(vol, vol_min, vol_max));
  
  return output_buffer;
	   
}

int convert_range(long val, long min, long max) {
  long range = max - min;

  if (range == 0)
    return 0;

  val -= min;
  return rint((double)val/(double)range * 100);
}
  

